<script setup>
import { computed, ref } from "vue";
import { getSellerInfo, sellerCommentPage, addBuyerConcern, shopIndexComment, getShopIndexInfo } from "~/api/user";
import { shopIndexGoodsList } from "~/api/goods"
import { useUserStore } from "~/store/useUser";
import { useSocketStore } from "~/store/useSocket"
import { useImageCache } from "~/composables/useImageCache"
import defaultAvatar from "~/assets/app-mj.png"

const router = useRouter();
const userStore = useUserStore();
const socketStore = useSocketStore();
const { getCoverImage, preloadImages, imageUrlCache } = useImageCache();
useSeoMeta({
  title: "卖家主页 - 技能猴子",
  ogTitle: "卖家主页 - 技能猴子",
  description: "技能猴子，找技能服务，我喜欢和技能人才直接聊",
  ogDescription: "技能猴子，找技能服务，我喜欢和技能人才直接聊",
});

// 获取卖家信息
const userInfoBase = ref({});
const shopIndexInfo = ref({}); // 新增：店铺主页信息
const userId = computed(() => router.currentRoute.value.query.uid);
console.log(userId.value);
const getSkillUserInfo = async () => {
  try {
    // const res = await getSellerInfo({
    //   sysUserId: userId.value,
    // });
    // userInfoBase.value = res.data;
    // focusStatus.value = userInfoBase.value.buyerInfo?.concernFlag
    // 获取店铺主页信息
    await getShopIndexInfoData();
    getSellerGoods()
  } catch (error) {
    console.log(error);
  }
};

// 获取店铺主页信息
const getShopIndexInfoData = async () => {
  try {
    const res = await getShopIndexInfo({
      shopId: userId.value,
    });
    if (res.code === 200) {
      shopIndexInfo.value = res.data || {};
    } else {
      console.error('获取店铺主页信息失败:', res.msg);
      ElMessage.error(res.msg || '获取店铺主页信息失败');
    }
  } catch (error) {
    console.error('获取店铺主页信息失败:', error);
    ElMessage.error('获取店铺主页信息失败，请稍后重试');
  }
};

// 获取卖家商品列表
const goodsList = ref([])
const goodsLoading = ref(false)
const goodsPageNum = ref(1)
const goodsPageSize = ref(20)
const goodsTotal = ref(0)
const goodsOrderBy = ref('desc')
const goodsOrderByColumn = ref('')

const currentShopId = computed(() => shopIndexInfo.value?.shopId || userId.value)

const getSellerGoods = async () => {
  try {
    goodsLoading.value = true
    const params = {
      pageNum: goodsPageNum.value,
      pageSize: goodsPageSize.value,
      shopId: currentShopId.value,
      isAsc: goodsOrderBy.value,
      orderByColumn: goodsOrderByColumn.value
    }
    
    // 清理空参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key];
      }
    });
    
    const res = await shopIndexGoodsList(params)
    if (res.code === 200) {
      // 为每个商品补充店铺信息
      const enrichedGoods = (res.rows || []).map(item => ({
        ...item,
        shopName: userInfo.value?.nickName || '未知店铺',
        shopAvatar: userInfo.value?.profile || '',
        level: userInfo.value?.level || 1,
        isBond: userInfo.value?.isBond || false,
        uimKey: userInfo.value?.sysUserId || userId.value
      }))
      
      goodsList.value = enrichedGoods
      goodsTotal.value = res.total || 0
    } else {
      console.error('获取商品列表失败:', res.msg)
      ElMessage.error(res.msg || '获取商品列表失败')
    }
  } catch (err) {
    console.error('获取商品列表失败:', err)
    ElMessage.error('获取商品列表失败，请稍后重试')
  } finally {
    goodsLoading.value = false
  }
}

onMounted(() => {
  getSkillUserInfo();
  getComments();
});

const userInfo = computed(() => {
  // 合并原有的买家信息和新的店铺主页信息
  const buyerInfo = userInfoBase.value?.buyerInfo || {};
  const shopInfo = shopIndexInfo.value || {};
  
  return {
    ...buyerInfo,
    ...shopInfo,
    // 保持一些字段的兼容性映射
    sysUserId: buyerInfo.sysUserId || shopInfo.userId,
    nickName: buyerInfo.nickName || shopInfo.shopName,
    profile: buyerInfo.profile || shopInfo.shopAvatar,
    // 新增的店铺主页信息字段
    creditLevel: shopInfo.creditLevel,
    creditScore: shopInfo.creditScore,
    depositStatus: shopInfo.depositStatus,
    depositAmount: shopInfo.depositAmount,
    orderCount: shopInfo.orderCount,
    onlineStatus: shopInfo.onlineStatus,
    replyRate: shopInfo.replyRate,
    isFollowed: shopInfo.isFollowed,
    followCount: shopInfo.followCount,
    type: shopInfo.type,
    schoolName: shopInfo.schoolName,
    skillNames: shopInfo.skillNames
  };
});

const profileImg = computed(() => {
  const src = userInfo.value?.shopAvatar || userInfo.value?.avatar || userInfo.value?.profile
  return getCoverImage(src)
})

const commentType = ref(null);
const orderBy = ref('desc'); // 排序方向
const orderByColumn = ref(''); // 排序列
const pageSize = ref(10);
const pageNum = ref(1);

// 评论统计数据
const commentCount = ref(0);
const goodCommentCount = ref(0);
const mediumCommentCount = ref(0);
const badCommentCount = ref(0);

const commentList = ref([]);

const getCommentTypeList = (type) => {
  commentType.value = type === 0 ? 0 : type;
  pageNum.value = 1;
  getComments();
};

const activeSort = (type) => {
  if (type === 0) {
    // 默认排序
    orderBy.value = 'desc';
    orderByColumn.value = '';
  } else if (type === 1) {
    // 最新评价 - 按评论时间排序
    orderBy.value = 'desc';
    orderByColumn.value = 'buyerCommentTime';
  }
  pageNum.value = 1;
  getComments();
};

const currentChange = (page) => {
  pageNum.value = page;
  getComments();
};

// 商品分页处理
const handleGoodsPageChange = (page) => {
  goodsPageNum.value = page;
  getSellerGoods();
};

// 商品排序处理
const handleGoodsSort = (sortColumn) => {
  goodsOrderByColumn.value = sortColumn;
  if (sortColumn === '') {
    // 默认排序
    goodsOrderBy.value = '';
  } else {
    // 其他排序都按降序
    goodsOrderBy.value = 'desc';
  }
  goodsPageNum.value = 1; // 重置到第一页
  getSellerGoods();
};

// 获取评价列表
const loading = ref(false);
const getComments = async () => {
  try {
    loading.value = true;
    const params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      shopId: currentShopId.value,
      isAsc: orderBy.value,
      orderByColumn: orderByColumn.value,
      type: commentType.value || 0
    };
    
    // 清理空参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key];
      }
    });
    
    const res = await shopIndexComment(params);
    if (res.code === 200) {
      const data = res.data;
      // 更新评论统计数据
      commentCount.value = data.commentCount || 0;
      goodCommentCount.value = data.goodCommentCount || 0;
      mediumCommentCount.value = data.mediumCommentCount || 0;
      badCommentCount.value = data.badCommentCount || 0;
      
      // 更新评论列表（处理图片与头像的 OSS ID → URL）
      if (data.commentInfoList && data.commentInfoList.records) {
        const records = data.commentInfoList.records
        const allOssIds = []
        records.forEach((item) => {
          if (item.picArray && Array.isArray(item.picArray)) {
            item.picArray.forEach((pic) => {
              if (pic && typeof pic === 'object' && pic.ossId) {
                allOssIds.push(pic.ossId)
              } else if (typeof pic === 'string' && !pic.includes('http')) {
                allOssIds.push(pic)
              }
            })
          }
          if (item.buyerAvatar && typeof item.buyerAvatar === 'string' && !item.buyerAvatar.includes('http')) {
            allOssIds.push(item.buyerAvatar)
          }
          if (item.buyerProfile && typeof item.buyerProfile === 'string' && !item.buyerProfile.includes('http')) {
            allOssIds.push(item.buyerProfile)
          }
        })
        if (allOssIds.length > 0) {
          await preloadImages(allOssIds)
        }
        const processed = records.map((item) => {
          const next = { ...item }
          if (next.picArray && Array.isArray(next.picArray)) {
            next.picArray = next.picArray.map((pic) => {
              if (pic && typeof pic === 'object' && pic.ossId) {
                const cached = imageUrlCache.value?.[pic.ossId]
                return cached || getCoverImage(pic.ossId)
              }
              if (typeof pic === 'string') {
                if (pic.includes('http')) return pic
                const cached = imageUrlCache.value?.[pic]
                return cached || getCoverImage(pic)
              }
              return ''
            }).filter(Boolean)
          }
          if (next.buyerAvatar && typeof next.buyerAvatar === 'string' && !next.buyerAvatar.includes('http')) {
            const cached = imageUrlCache.value?.[next.buyerAvatar]
            next.buyerAvatar = cached || getCoverImage(next.buyerAvatar)
          }
          if (next.buyerProfile && typeof next.buyerProfile === 'string' && !next.buyerProfile.includes('http')) {
            const cached = imageUrlCache.value?.[next.buyerProfile]
            next.buyerProfile = cached || getCoverImage(next.buyerProfile)
          }
          return next
        })
        commentList.value = processed
      } else {
        commentList.value = []
      }
    } else {
      console.error('获取评论失败:', res.msg);
      ElMessage.error(res.msg || '获取评论失败');
    }
  } catch (error) {
    console.error("获取评价列表失败", error);
    ElMessage.error('获取评论失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};
// 去详情页面
const toDetails = (dataItem) => {
  router.push({
    path: "/details",
    query: {
      id: dataItem.id,
    },
  });
};
// 关注
const focusHandle = async ()=>{
  try{
    await addBuyerConcern({
      goodsUserId: userInfo.value.sysUserId,
    });
    // 更新店铺主页信息中的关注状态
    if (shopIndexInfo.value) {
      shopIndexInfo.value.isFollowed = !shopIndexInfo.value.isFollowed;
      // 更新关注数量
      if (shopIndexInfo.value.isFollowed) {
        shopIndexInfo.value.followCount = (shopIndexInfo.value.followCount || 0) + 1;
      } else {
        shopIndexInfo.value.followCount = Math.max((shopIndexInfo.value.followCount || 0) - 1, 0);
      }
    }
  }catch(error){
    console.log(error);
  }
}

// 立即咨询
const createChatStatus = ref(false);
const toIM = () => {
  if (createChatStatus.value) {
    return;
  }
  createChatStatus.value = true;
  if (!userStore.getToken) {
    router.push("/login");
    return;
  }
  if (userInfo.value.uimKey) {
    socketStore.setCurrentImKey(userInfo.value.uimKey);
    socketStore.sendMessage(
      "chatMsg",
      {
        to: userInfo.value.uimKey,
        content: "现在可以开始沟通了",
        contentType: 4,
      },
      () => {
        setTimeout(() => {
          createChatStatus.value = false;
          router.push(`/chat?id=${userInfo.value.sysUserId}&type=4`);
        }, 1000);
      }
    );
  }
};

const educationsData = computed(()=>{
  if(userInfo.value.salerInfo && userInfo.value.salerInfo.educations){
    const educations = userInfo.value.salerInfo.educations.sort((a,b)=> b.graduateTime - a.graduateTime)
    return educations[0]
  }
  return {}
})

// 信用等级文本映射
const creditLevelText = computed(() => {
  const levelMap = {
    0: '普通',
    1: '较好', 
    2: '优秀',
    3: '极好',
    4: '完美'
  }
  return levelMap[userInfo.value?.creditLevel] || '普通'
})

// 教育类型文本映射
const educationTypeText = computed(() => {
  const typeMap = {
    0: '小学',
    1: '初中', 
    2: '高中',
    3: '大专',
    4: '本科',
    5: '硕士研究生',
    6: '博士研究生'
  }
  return typeMap[userInfo.value?.type] || '未知'
})

// 在线状态
const isOnline = computed(() => {
  return userInfo.value?.onlineStatus === 1
})
</script>

<template>
  <div class="user-home-page">
    <BaseHeaderMenuWhite bg-color="white" />
    <div class="user">
      <div class="user-info" v-if="userInfo">
        <el-image v-if="profileImg" class="head" :src="profileImg" alt="">
          <template #error>
            <img class="head" :src="defaultAvatar" alt="" />
          </template>
        </el-image>
        <img v-else class="head" :src="defaultAvatar" alt="" />
        <div class="info">
          <p class="name">
            <span class="name-txt">{{ userInfo.shopName || userInfo.nickName || userInfo.phonenumber }}</span>
            <span class="focus">{{ userInfo.followCount || 0 }}人关注</span>
            <span v-if="isOnline" class="online-status">在线</span>
          </p>
          <p class="career">
            <span class="school" v-if="userInfo.schoolName || educationsData.schoolName">
              {{ userInfo.schoolName || educationsData.schoolName }}·{{ educationTypeText }}
            </span>
            <span v-for="skill in userInfo.skillNames" :key="skill" class="btn">{{ skill }}</span>
          </p>
        </div>
      </div>
      <div class="user-data" v-if="userInfo">
        <div class="item">
          <p>信用等级</p>
          <p>{{ creditLevelText }}</p>
          <p>分值 {{ userInfo.creditScore || 0 }}</p>
        </div>
        <span class="line"></span>
        <div class="item">
          <p>总销量</p>
          <p>{{ userInfo.orderCount || 0 }}</p>
          <p>3分钟回复率 {{ (userInfo.replyRate || 0) * 100 }}%</p>
        </div>
        <span class="line"></span>
        <div class="item">
          <p>保证金状态</p>
          <p>{{ userInfo.depositStatus ? '已缴纳' : '未缴纳' }}</p>
          <p v-if="userInfo.depositAmount">金额 ¥{{ userInfo.depositAmount }}</p>
        </div>
      </div>
      <div class="more-btn" v-if="false">
        <span :class="[userInfo.isFollowed ? 'focus-btn-active' : 'focus-btn']"  @click="focusHandle">{{userInfo.isFollowed ? '已关注' : '关注'}}</span>
        <span class="message-btn" @click="toIM">发消息</span>
      </div>
    </div>
    <h3 class="title-h">商品 ({{ goodsTotal || 0 }})</h3>
    <!-- 商品排序 -->
    <div class="goods-sort-box">
      <div class="sort-options">
        <span :class="{ active: goodsOrderByColumn === '' }" @click="handleGoodsSort('')">默认排序</span>
        <span :class="{ active: goodsOrderByColumn === 'salesCount' }" @click="handleGoodsSort('salesCount')">销量排序</span>
        <span :class="{ active: goodsOrderByColumn === 'score' }" @click="handleGoodsSort('score')">评分排序</span>
      </div>
    </div>
    <div class="goods-list" v-loading="goodsLoading">
      <RecommendingItem
        v-for="item of goodsList"
        :key="item.goodsId"
        :dataItem="item"
        @refresh="toDetails"
      />
    </div>
    <!-- 商品分页 -->
    <div class="goods-pagination" v-if="goodsTotal > goodsPageSize">
      <el-pagination
        v-model:current-page="goodsPageNum"
        :page-size="goodsPageSize"
        :total="goodsTotal"
        layout="prev, pager, next"
        @current-change="handleGoodsPageChange"
      />
    </div>
    <div class="evaluate-list">
      <div class="evaluate-page">
        <div class="header">
          <p class="title">获得评价（{{ commentCount || 0 }}）</p>
          <div class="sort-box">
            <p class="filter">
              <span :class="{ active: !commentType }" @click="getCommentTypeList(0)"
                >全部({{ commentCount || 0 }})</span
              >
              <span :class="{ active: commentType === 1 }" @click="getCommentTypeList(1)"
                >好评({{ goodCommentCount || 0 }})</span
              >
              <span :class="{ active: commentType === 2 }" @click="getCommentTypeList(2)"
                >中评({{ mediumCommentCount || 0 }})</span
              >
              <span :class="{ active: commentType === 3 }" @click="getCommentTypeList(3)"
                >差评({{ badCommentCount || 0 }})</span
              >
            </p>
            <div class="sort">
              <span :class="{ active: orderByColumn === '' }" @click="activeSort(0)"
                >默认排序</span
              >
              <span :class="{ active: orderByColumn === 'buyerCommentTime' }" @click="activeSort(1)"
                >最新评价</span
              >
            </div>
          </div>
        </div>
        <div v-loading="loading">
          <MyEvaluationItem v-for="item in commentList" :key="item.id" :itemData="item" />
          <el-empty v-if="!commentList || commentList.length === 0"></el-empty>
        </div>
        <div class="paging-box">
          <el-pagination
            background
            layout="prev, pager, next"
            :page-size="pageSize"
            :total="commentCount"
            :current-page="pageNum"
            @current-change="currentChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.user-home-page {
  display: flex;
  flex-direction: column;
  width: 1200px;
  margin: 0 auto;
  padding-top: 112px;
}
.user {
  display: flex;
  align-items: center;
  background: #ffffff;
  border-radius: 16px 16px 16px 16px;
  border: 1px solid rgba(25, 30, 40, 0.08);
  padding: 20px 30px;
}

.user-info {
  flex: 1;
  display: flex;
  align-items: center;

  .head {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    margin-right: 12px;
  }

  .info {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: 55px;

    .name-txt {
      color: #191e28;
      font-size: 20px;
      font-weight: bold;
    }

    .focus {
      color: rgba(25, 30, 40, 0.48);
      margin-left: 12px;
    }

    .online-status {
      color: #1dbf73;
      background: rgba(29, 191, 115, 0.1);
      padding: 2px 6px;
      border-radius: 4px;
      font-size: 12px;
      margin-left: 8px;
    }

    .school {
      color: #191e28;
      margin-right: 8px;
    }

    .btn {
      padding: 2px 8px;
      color: rgba(25, 30, 40, 0.48);
      border: 1px solid rgba(25, 30, 40, 0.08);
      font-size: 12px;
      border-radius: 4px 4px 4px 4px;
      margin-right: 5px;
      &:last-child{
        margin-right: 0;
      }
    }
  }
}

.user-data {
  display: flex;
  align-items: center;

  .line {
    width: 1px;
    height: 40px;
    background: rgba(25, 30, 40, 0.08);
    margin: 0 40px;
  }

  .item {
    p:nth-child(1) {
      font-size: 12px;
      color: rgba(25, 30, 40, 0.48);
    }

    p:nth-child(2) {
      font-size: 18px;
      color: #191e28;
      font-weight: 600;
      margin: 3px 0;
    }

    p:nth-child(3) {
      font-size: 12px;
      color: rgba(25, 30, 40, 0.48);
    }
  }
}

.more-btn{
  margin-left: 70px;
  .focus-btn{
    display: inline-block;
    width: 92px;
    height: 36px;
    background: #1DBF73;
    border-radius: 8px 8px 8px 8px;
    text-align: center;
    line-height: 36px;
    color: #fff;
    margin-right: 12px;
    cursor: pointer;
  }
  .focus-btn-active{
    display: inline-block;
    width: 92px;
    height: 36px;
    background: #FFFFFF;
    border-radius: 8px 8px 8px 8px;
    border: 1px solid rgba(25,30,40,0.08);
    text-align: center;
    line-height: 36px;
    color: #191E28;
    margin-right: 12px;
    cursor: pointer;
    &:hover{
      background: #1DBF73;
      color: #fff;
    }
  }
  .message-btn{
    display: inline-block;
    width: 92px;
    height: 36px;
    background: #FFFFFF;
    border-radius: 8px 8px 8px 8px;
    border: 1px solid rgba(25,30,40,0.08);
    text-align: center;
    line-height: 36px;
    color: #191E28;
    cursor: pointer;
  }
}

.title-h {
  margin: 32px 0 16px;
}
.goods-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); /* 根据需要调整列宽 */
  gap: 10px; /* 设置网格项之间的间隙 */
}
.goods-pagination {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}

.goods-sort-box {
  margin: 16px 0;
  
  .sort-options {
    display: flex;
    gap: 20px;
    
    span {
      padding: 8px 16px;
      color: rgba(25, 30, 40, 0.6);
      background: rgba(25, 30, 40, 0.02);
      border-radius: 6px;
      cursor: pointer;
      transition: all 0.3s ease;
      
      &:hover {
        background: rgba(25, 30, 40, 0.05);
      }
      
      &.active {
        color: #1dbf73;
        background: rgba(29, 191, 115, 0.1);
        font-weight: bold;
      }
    }
  }
}
.evaluate-list {
  flex: 1;
  background: #ffffff;
  border-radius: 16px 16px 16px 16px;
  border: 1px solid rgba(25, 30, 40, 0.08);
  margin-top: 16px;
  overflow-y: auto;
  padding: 40px;
  box-sizing: border-box;
  margin-bottom: 60px;
  .evaluate-page {
    max-width: 1200px;
  }
  .header {
    .title {
      color: #191e28;
      font-size: 20px;
      font-weight: bold;
      margin-bottom: 20px;
    }
    .sort-box {
      display: flex;
      align-items: center;
      span {
        line-height: 12px;
        cursor: pointer;
        &:nth-child(1) {
          padding-right: 12px;
          margin-right: 12px;
          border-right: 1px solid rgba(25, 30, 40, 0.08);
        }
      }
      .sort {
        color: #191e28;
      }
      .active {
        color: #1dbf73;
        font-weight: bold;
      }
    }
    .filter {
      flex: 1;
      margin-bottom: 20px;
      span {
        padding: 4px 8px;
        color: rgba(25, 30, 40, 0.6);
        background: rgba(25, 30, 40, 0.02);
        border-radius: 6px 6px 6px 6px;
        margin-right: 12px;
        &.active {
          color: #1dbf73;
          background: rgba(29, 191, 115, 0.08);
        }
      }
    }
  }
}
.paging-box {
  display: flex;
  align-items: center;
  justify-content: center;
  padding-top: 20px;
}
</style>
